import maya.cmds as cmds

import JTK.jmaya.core as jmcore
import JTK.jQt.MessageWidget.MessageBox as mb

import importlib
importlib.reload(jmcore)
importlib.reload(mb)


def multi_node_set_attr(node_list, attr, value):

    # selected = cmds.ls(sl=1)
    if not node_list:
        cmds.warning('请选择需要执行的物体！')
    for nn in node_list:
        node = jmcore.BaseNode(nn)
        if not node.has_attr(attr):
            info = '{}这个属性不存在，检查是否输入有误'.format(attr)
            if attr.startswith('.'):
                info += '\n注意属性前面不要加点(.)'
            mb.MessageBox().error(info)
            cmds.error(info)
            break
        if attr == 'aiMatte' and node.type() == 'aiStandIn':
            if node.get_attr('aiMatte') == 0:
                node.set_attr('overrideMatte', 1)
        node.set_attr(attr, value)
        # cmds.setAttr('{}.overrideMatte'.format(s), 1)
        # cmds.setAttr('{}.aiAov'.format(s), 'TOMHDBounce')
    info = '批量执行完 %d 个节点\n %s=%s' % (len(node_list), attr, value)
    mb.MessageBox().info(info)
    jmcore.info(node_list)


def set_sl_node(attr, value, _type=None):
    selected = cmds.ls(sl=1)
    node_list = []
    if _type:
        _type = get_type(_type)
        for s in selected:
            node_list.extend(cmds.listRelatives(s, ad=1, type=_type))
            if cmds.objectType(s) == _type:
                node_list.append(s)
    else:
        node_list = selected
    multi_node_set_attr(node_list, attr, value)


def set_all_node(attr, value, _type):
    if not _type:
        cmds.warning('必须要有过滤类型才能执行整个场景遍历操作！')
    else:
        _type = get_type(_type)
        all_node = cmds.ls(type=_type)
        # print(all_node)
        multi_node_set_attr(all_node, attr, value)


def get_type(_type):
    if _type == 'light':
        import maya.app.renderSetup.lightEditor.model.typeManager as typeMgr
        typeMgr.rebuild()
        return typeMgr.lights()
    elif _type == 'from selected':
        selected = cmds.ls(sl=1)
        if selected:
            sl = selected[0]
            get_select_type = cmds.objectType(sl)
            return get_select_type
        else:
            cmds.error('have no selected.')
            return None
    else:
        return _type
